package com.aso114.project.exam;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.EvenBaseBean;
import com.aso114.project.bean.MsgEvent;
import com.aso114.project.bean.QuestionBaseBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.commonview.NoPreloadViewPager;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.MySharedPreferences;
import com.aso114.project.util.SystemBarHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Error_Analysis_Activity extends BaseSimpleActivity {
    public static final String IS_EXAM = "is_exam";
    public static NoPreloadViewPager viewPager;
    @BindView(R.id.question_back)
    ImageView back;
    @BindView(R.id.question_countdown)
    TextView timer;
    @BindView(R.id.question_timer)
    LinearLayout timerLayout;

    @BindView(R.id.question_submit)
    TextView submit;
    @BindView(R.id.settingtv)
    TextView setting;
    @BindView(R.id.main_bar)
    LinearLayout mainBar;
    boolean isExam;
    @BindView(R.id.stop)
    TextView stop;
    @BindView(R.id.collect)
    TextView collect;

    TextView first, second, three, four, five;
    public static QuestionBean qdata;
    @BindView(R.id.que_conect)
    TextView queConect;
    @BindView(R.id.que_num)
    TextView queNum;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.titletv)
    TextView titletv;
    @BindView(R.id.question_toolbar)
    RelativeLayout questionToolbar;
    @BindView(R.id.main_viewpager)
    NoPreloadViewPager mainViewpager;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.remove)
    TextView remove;

    private DefineTimer countDownTimer;
    boolean isstart = false;
    Intent intent;
    Dialog dialog;
    public static Error_Analysis_Activity instance;
    public static ArrayList<QuestionBaseBean> baseBean = new ArrayList<>();

    private int pagerPosition = 0;
    private int position = 0;
    // 是否解析可见
    private boolean isAnalysis;
    private boolean isAnalysisOpen;
    private boolean isReportTo;


    @Override
    protected int getResouseId() {
        return R.layout.question_main;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this);
        SystemBarHelper.setHeightAndPadding(this, questionToolbar);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(this, 0);
            SystemBarHelper.setStatusBarDarkMode(this);
        }
        instance = this;
        isAnalysis = getIntent().getBooleanExtra("isAnalysis", false);
        isAnalysisOpen = getIntent().getBooleanExtra("isAnalysisOpen", false);
        isReportTo = getIntent().getBooleanExtra("isReportTo", false);
        position = getIntent().getIntExtra("position", 0);
        viewPager = (NoPreloadViewPager) findViewById(R.id.main_viewpager);
        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        viewPager.setOnPageChangeListener(new MyPagerChangeListner());
        isExam = getIntent().getBooleanExtra(IS_EXAM, false);

        String type = getIntent().getStringExtra("titletype");
        titletv.setVisibility(View.VISIBLE);
        if ("1".equals(type)) {
            titletv.setText("错题解析");
        } else {

            titletv.setText("全部解析");
        }

        timerLayout.setVisibility(View.GONE);
        submit.setVisibility(View.GONE);
        stop.setVisibility(View.GONE);

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(EvenBaseBean event) {
        Log.i("yxp", "------------------1");
        if (event != null) {
            if (event.getType() == 1) {
                baseBean = event.getBaseBean();
                queConect.setText(baseBean.get(viewPager.getCurrentItem()).getTitle());
                queNum.setText((viewPager.getCurrentItem() + 1) + "/" + baseBean.size());
                viewPager.setCurrentItem(position, false);
                judgeCollect(position);
            }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }


    private long currentTime = 120 * 60 * 1000;

    public void startTimer() {
        countDownTimer = new DefineTimer(currentTime, 1000) {//2700 45分钟
            @Override
            public void onTick(long l) {
                currentTime = l;
                int allSecond = (int) l / 1000;//秒
                int hour = allSecond / 3600;
                int minute = allSecond / 60 - hour * 60;
                int second = allSecond - (hour * 60 + minute) * 60;
                timer.setText("倒计时 " + hour + ":" + minute + ":" + second);
            }

            @Override
            public void onFinish() {
                submitAnswer();
            }
        };
        countDownTimer.start();


    }


    @Override
    protected void onPause() {
        if (isExam) {
            countDownTimer.cancel();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (isExam) {
            startTimer();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (isExam) {
            countDownTimer.cancel();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static void nextQuestion() {
        if (viewPager.getCurrentItem() <= baseBean.size()) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.question_back, R.id.question_submit, R.id.settingtv, R.id.main_bar, R.id.stop,
            R.id.collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.question_back:

                if (isExam)
                    backHandler();
                else
                    Error_Analysis_Activity.this.finish();
                break;
            case R.id.question_submit:
                //                backHandler();
                intent = new Intent(Error_Analysis_Activity.this, AnswerCardActivity.class);
                startActivity(intent);
                break;
            case R.id.settingtv:
                showProductDialog();
                break;
            case R.id.stop:
                final View dialogview = Error_Analysis_Activity.this.getLayoutInflater().inflate(
                        R.layout.stopclock_xml, null);
                dialog = new Dialog(Error_Analysis_Activity.this, R.style.dialogStyle1);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();

                dialogview.findViewById(R.id.keep).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                                //继续倒计时，那么就需要减去之前的
                                countDownTimer = new DefineTimer(currentTime, 1000) {//2700 45分钟
                                    @Override
                                    public void onTick(long l) {
                                        currentTime = l;
                                        int allSecond = (int) l / 1000;//秒
                                        int hour = allSecond / 3600;
                                        int minute = allSecond / 60 - hour * 60;
                                        int second = allSecond - (hour * 60 + minute) * 60;
                                        timer.setText("倒计时 " + hour + ":" + minute + ":" + second);
                                    }

                                    @Override
                                    public void onFinish() {
                                        submitAnswer();
                                    }
                                };
                                countDownTimer.start();

                                isstart = false;
                            }
                        });

                dialogview.findViewById(R.id.dialog_ok).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                //暂停
                if (isstart == false) {
                    countDownTimer.cancel();
                    isstart = true;
                } else {

                }
                break;
            case R.id.main_bar:

                break;
            case R.id.collect:
                if (baseBean.get(pagerPosition).isCollect() == false) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.aff6559));
                    baseBean.get(pagerPosition).setCollect(true);
                    setCollect();
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                            .getMinimumHeight());

                    collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
                    collect.setTextColor(getResources().getColor(R.color.a999999));
                    baseBean.get(pagerPosition).setCollect(false);
                    delCollect();
                }
                break;
        }
    }

    private void delCollect() {
        CommentModel.getInstant().delCollect(Constant.adutst, baseBean.get(pagerPosition).getRealQuestionId(), new
                CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        Helper.showToast("取消收藏");
                    }

                    @Override
                    public void onFailure(String fail) {

                    }
                });
    }

    private void setCollect() {
        CommentModel.getInstant().setCollect(Constant.adutst, baseBean.get(pagerPosition).getRealQuestionId(), new
                CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        Helper.showToast("已收藏");
                    }

                    @Override
                    public void onFailure(String fail) {

                    }
                });
    }


    //设置字体大小
    private void showProductDialog() {

        View view = LayoutInflater.from(Error_Analysis_Activity.this).inflate(R.layout
                .questionseting, null);

        first = (TextView) view.findViewById(R.id.first);
        second = (TextView) view.findViewById(R.id.second);
        three = (TextView) view.findViewById(R.id.three);
        four = (TextView) view.findViewById(R.id.four);
        five = (TextView) view.findViewById(R.id.five);

        int size = MySharedPreferences.getInstance(Error_Analysis_Activity.this).getTextSize();
        switch (size) {
            case 1:
                textSelect(first);
                break;
            case 2:
                textSelect(second);
                break;
            case 3:
                textSelect(three);
                break;
            case 4:
                textSelect(four);
                break;
            case 5:
                textSelect(five);
                break;
        }
        // 创建PopupWindow对象，指定宽度和高度
        PopupWindow window = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT);

        // 设置可以获取焦点
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        // 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
        // 更新popupwindow的状态
        window.update();
        // 以下拉的方式显示，并且可以设置显示的位置
//        window.showAsDropDown(tvProduct, 0, 20);
//        window.showAtLocation(setting, Gravity.CENTER | Gravity.BOTTOM, 0, 160);
        int[] location = new int[2];
        mainBar.getLocationOnScreen(location);
        //获取popwindow宽高
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = view.getMeasuredWidth();
        int popupHeight = view.getMeasuredHeight();
        //在控件上方显示
        window.showAtLocation(mainBar, Gravity.NO_GRAVITY, (location[0] + mainBar.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight);

        view.findViewById(R.id.first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 1));
                MySharedPreferences.getInstance(Error_Analysis_Activity.this).setTextSize(1);
                textSelect(first);
            }
        });

        view.findViewById(R.id.second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 2));
                MySharedPreferences.getInstance(Error_Analysis_Activity.this).setTextSize(2);
                textSelect(second);
            }
        });


        view.findViewById(R.id.three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 3));
                MySharedPreferences.getInstance(Error_Analysis_Activity.this).setTextSize(3);
                textSelect(three);
            }
        });

        view.findViewById(R.id.four).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 4));
                MySharedPreferences.getInstance(Error_Analysis_Activity.this).setTextSize(4);
                textSelect(four);
            }
        });

        view.findViewById(R.id.five).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MsgEvent(viewPager.getCurrentItem(), 5));
                MySharedPreferences.getInstance(Error_Analysis_Activity.this).setTextSize(5);
                textSelect(five);
            }
        });

    }

    private void textSelect(TextView view) {
        first.setSelected(false);
        second.setSelected(false);
        three.setSelected(false);
        four.setSelected(false);
        five.setSelected(false);
        view.setSelected(true);
    }


    class MyPagerChangeListner implements NoPreloadViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            queConect.setText(baseBean.get(position).getTitle());
            queNum.setText((position + 1) + "/" + baseBean.size());
        }

        @Override
        public void onPageSelected(int position) {
            pagerPosition = position;
            queConect.setText(baseBean.get(position).getTitle());
            queNum.setText((position + 1) + "/" + baseBean.size());
            judgeCollect(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private void judgeCollect(int position) {
        if (baseBean.get(position).isCollect() == true) {
            Drawable drawable = getResources().getDrawable(R.mipmap.erji_scfk_ic);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                    .getMinimumHeight());

            collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
            collect.setTextColor(getResources().getColor(R.color.aff6559));
        } else {
            Drawable drawable = getResources().getDrawable(R.mipmap.erji_sc_ic);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable
                    .getMinimumHeight());

            collect.setCompoundDrawables(null, drawable, null, null);  //设置到控件的上面
            collect.setTextColor(getResources().getColor(R.color.a999999));
        }
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return QuestionsFragment.newInstance(position, isAnalysis, isAnalysisOpen, isReportTo);
        }

        @Override
        public int getCount() {
            if (baseBean == null || baseBean.size() == 0) {
                return 0;
            } else {
                return baseBean.size();
            }
        }
    }


    static int rightCount;
    static int errorCount;

    public static void upDataRightAndError() {
        rightCount = 0;
        errorCount = 0;
        for (QuestionBaseBean result : baseBean) {
            if (result.isFinishAnswer()) {
                if (result.isChooseResult()) {
                    rightCount++;
                } else {
                    errorCount++;
                }
            }
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isExam) {
            backHandler();
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    public void backHandler() {
        finish();

    }


    //提交答案
    public void submitAnswer() {
//        finish();
    }


}

